package com.wyc.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.wyc.entity.ShopType;
import com.wyc.mapper.ShopTypeMapper;
import com.wyc.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.wyc.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *

 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryByAsc() {
        // 从redis 获取缓存
        String shopTypeJSON = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        // 如果存在直接返回
        if (StrUtil.isNotBlank(shopTypeJSON)) {
            // 将JSON字符串转换为List<ShopType>
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJSON, ShopType.class);
            return shopTypes;
        }
        // 不存在，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        if (shopTypes.isEmpty()) {
            return null;
        }
        // 写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypes));
        // 返回结果
        return shopTypes;
    }
}
